package org.example.liuy.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.util.concurrent.Semaphore;

public class RateLimitHandler implements HttpHandler {
    private final HttpHandler next;
    private final Semaphore semaphore; // 信号量限流

    public RateLimitHandler(HttpHandler next) {
        this.next = next;
        // 限制并发请求数为1000
        this.semaphore = new Semaphore(1000);
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        if (semaphore.tryAcquire()) {
            try {
                next.handle(exchange);
            } finally {
                semaphore.release();
            }
        } else {
            // 限流响应
            exchange.sendResponseHeaders(429, 0); // Too Many Requests
            exchange.getResponseBody().close();
        }
    }
}